package tcc.wa.persistence.dao;

import java.util.ArrayList;
import java.util.List;

import tcc.wa.model.Alert;
import tcc.wa.model.AlertType;
import tcc.wa.model.util.AlertTypeUtils;
import tcc.wa.persistence.dao.base.DAOBase;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * Data access object class responsible for Alert persistence management.
 */
public class AlertDAO extends DAOBase {

	public AlertDAO(Context context) {
		super(context);
	}
	
	/**
	 * Finds all alerts on the database.
	 *
	 * @return all the alerts
	 */
	public List<Alert> findAll() {
		List<Alert> alerts = new ArrayList<Alert>();
		SQLiteDatabase database = getWritableDatabase();
		Cursor cursor = database.query(ALERT_TABLE_NAME, null, null, null, null, null, null);
		while (cursor.moveToNext()) {
			Alert alert = new Alert();
			alert.setId(cursor.getLong(0));
			alert.setType(AlertTypeUtils.parse(cursor.getInt(1)));
			alert.setValue(cursor.getDouble(2));
			alert.setHoursInAdvance(cursor.getInt(3));
			alerts.add(alert);
		}
		close();
		return alerts;
	}
	
	/**
	 * Finds all the alerts of a given type.
	 *
	 * @param type the desired type
	 * @return all the alerts of a given type
	 */
	public List<Alert> findByType(AlertType type) {
		List<Alert> alerts = new ArrayList<Alert>();
		SQLiteDatabase database = getWritableDatabase();
		String alertTypeId = String.valueOf(AlertTypeUtils.convertToInt(type));
		Cursor cursor = database.query(ALERT_TABLE_NAME, null, "type = ?", new String[] { alertTypeId }, null, null, null);
		while (cursor.moveToNext()) {
			Alert alert = new Alert();
			alert.setId(cursor.getLong(0));
			alert.setType(AlertTypeUtils.parse(cursor.getInt(1)));
			alert.setValue(cursor.getDouble(2));
			alert.setHoursInAdvance(cursor.getInt(3));
			alerts.add(alert);
		}
		close();
		return alerts;
	}
	
	/**
	 * Saves an alert on the database.
	 *
	 * @param alert the alert to be saved
	 */
	public void save(Alert alert) {
		SQLiteDatabase database = getWritableDatabase();
		ContentValues alertValues = new ContentValues();
		alertValues.put("type", AlertTypeUtils.convertToInt(alert.getType()));
		alertValues.put("value", alert.getValue());
		alertValues.put("hours_advance", alert.getHoursInAdvance());
		long id = database.insert(ALERT_TABLE_NAME, null, alertValues);
		alert.setId(id);
		close();
	}
	
	/**
	 * Deletes an alert from the database.
	 *
	 * @param alertId id of the alert to be deleted.
	 */
	public void delete(long alertId) {
		SQLiteDatabase database = getWritableDatabase();
		database.delete(ALERT_TABLE_NAME, "id = ?", new String[] { String.valueOf(alertId) });
		close();
	}
}